package common.mybatis;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
        * JSON格式
        *
        */
public class JSONTypeHandler extends BaseTypeHandler<JSONObject> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JSONObject parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setString(i, (parameter == null ? null : parameter.toJSONString()));
    }

    @Override
    public JSONObject getNullableResult(ResultSet rs, String columnName) throws SQLException {

        String value = rs.getString(columnName);
        if(rs.wasNull()) {
            return null;
        }
        return StringUtils.isEmpty(value) ? null : JSONObject.parseObject(value);
    }

    @Override
    public JSONObject getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        if(rs.wasNull()) {
            return null;
        }
        return StringUtils.isEmpty(value) ? null : JSONObject.parseObject(value);
    }

    @Override
    public JSONObject getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return StringUtils.isEmpty(value) ? null : JSONObject.parseObject(value);
    }

}

